package com.sumfun.blog.controller;


import com.sumfun.blog.common.BaseResponse;
import com.sumfun.blog.common.ErrorCode;
import com.sumfun.blog.common.ResultUtils;
import com.sumfun.blog.exception.BusinessException;
import com.sumfun.blog.utils.LoginUtils;
import io.swagger.annotations.Api;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.util.DigestUtils;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import java.util.UUID;
import java.util.concurrent.TimeUnit;

@Api(value = "用户登录", tags = {"用户登录"})
@RestController
@RequestMapping("/user")
public class UserController {
    private static final String SALT = "sumfun";
    private static final long TOKEN_EXPIRE_TIME = 24 * 60 * 60; // 24小时过期

    @Autowired
    private RedisTemplate<String, String> redisTemplate;


    @PostMapping("/login")
    public BaseResponse<String> doLogin(@RequestParam String username, @RequestParam String password, HttpServletRequest request) {
        if(StringUtils.isAnyBlank(username, password)) {
            throw new BusinessException(ErrorCode.PARAMS_ERROR, "账户和密码不能为空");
        }
        if(password.length()  < 4) {
            throw new BusinessException(ErrorCode.PARAMS_ERROR, "密码不对");
        }
        //加密
        String encryptPassword = DigestUtils.md5DigestAsHex((SALT + password).getBytes());
        String passwordConst = DigestUtils.md5DigestAsHex((SALT + "123456").getBytes());

        //查询用户是否存在
        if (!"sumfun".equals(username) || !encryptPassword.equals(passwordConst)) {
            throw new BusinessException(ErrorCode.PARAMS_ERROR, "用户不存在或密码错误");
        }

        // 生成token
        String token = UUID.randomUUID().toString();

        // 将token存入redis，设置24小时过期
        redisTemplate.opsForValue().set(LoginUtils.TOKEN_PREFIX + token, username, TOKEN_EXPIRE_TIME, TimeUnit.SECONDS);

        return ResultUtils.success(token);
    }

    @GetMapping("/checkLogin")
    public BaseResponse<Boolean> checkLogin(HttpServletRequest request) {
        LoginUtils loginUtils = new LoginUtils();
        return ResultUtils.success(loginUtils.isLogin(request));
    }


    @PostMapping("/logout")
    public BaseResponse<Boolean> logout(@RequestHeader(value = "token", required = false) String token) {
        if (StringUtils.isBlank(token)) {
            return ResultUtils.success(true);
        }
        redisTemplate.delete("token:" + token);
        return ResultUtils.success(true);
    }
}
